package com.tc.dto;


import net.sf.json.JSONObject;

public class Envelope {
    private int code;//代码
    private String message;//提示信息
    private Object obj;//携带对象
    public static Envelope success=new Envelope(0,"success",null);//默认成功
    public static Envelope dbError=new Envelope(-1,"数据库错误！",null);//数据库错误
    public static Envelope systemError=new Envelope(-2,"系统错误！",null);;//系统错误
    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public Object getObj() {
        return obj;
    }
    public void setObj(Object obj) {
        this.obj = obj;
    }

    /**根据一个json字符串来构造一个Envelope对象
     *
     * @param object
     * @return
     */
    public static Envelope fromObject(Object object){
        JSONObject jsonObject=JSONObject.fromObject(object);
        Envelope envelope=new Envelope(jsonObject.getInt("code"), (String) jsonObject.getOrDefault("message","null"),jsonObject.get("object"));
        return envelope;
    }
    public Envelope(int code,String message,Object obj) {
        this.code=code;
        this.message=message;
        this.obj=obj;
    }
    public Envelope() {
    }

    /**默认的成功构造器
     *
     * @param object
     */
    public Envelope(Object object){
        this.code=0;
        this.message="success";
        this.obj=object;
    }
    @Override
    public String toString(){
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("code",this.code);
        jsonObject.put("message",message);
        jsonObject.put("object",this.obj);
        return jsonObject.toString();
    }

}